import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import Hls from 'hls.js';
import NPlayer from '@nplayer/react';
import Player, { ControlItem, Popover } from 'nplayer';

import { VideosValueType } from 'src/redux';

import './index.css';
import { Card } from 'antd';

export const PlayerWeb: React.FC<VideosValueType> = ({ id, name, source, actor, describe, pic }) => {
  const player = useRef(null);
  const anthology = useMemo(
    () =>
      source?.map((s) => {
        const allAddress = s.address.split('#');
        const address = allAddress.map((a) => {
          const add = a.split('$');
          return { current: add[0], address: add[1] };
        });

        return { flag: s.flag, address };
      }),
    [source],
  );

  const m3u8Anthology = useMemo(() => anthology?.find((an) => an.flag.includes('m3u8')), [anthology]);

  const [currentSourceAddress, setCurrentSourceAddress] = useState(m3u8Anthology?.address[0].address);

  const { Quantity, Screenshot } = useMemo(() => {
    const Screenshot = {
      html: '截图',
      click(player: Player) {
        const canvas = document.createElement('canvas');
        canvas.width = player.video.videoWidth;
        canvas.height = player.video.videoHeight;
        canvas.getContext('2d')!.drawImage(player.video, 0, 0, canvas.width, canvas.height);
        canvas.toBlob((blob) => {
          const dataURL = URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = dataURL;
          link.download = 'player.png';
          link.style.display = 'none';
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          URL.revokeObjectURL(dataURL);
        });
      },
    };

    const Quantity: ControlItem = {
      el: document.createElement('div'),
      init() {
        this.btn = document.createElement('div');
        this.btn.textContent = '选集';
        this.el.appendChild(this.btn);
        this.popover = new Popover(this.el);
        this.btn.addEventListener('click', () => this.popover.show());
        // 点击按钮的时候展示 popover
        this.el.style.display = 'none';
        // 默认隐藏
        this.el.classList.add('quantity');
      },
    };

    return { Screenshot, Quantity };
  }, []);

  const clickHandle = useCallback((event: React.MouseEvent<HTMLUListElement, MouseEvent>) => {
    const selectAddress = (event.target as HTMLElement).dataset.address;
    if (selectAddress) setCurrentSourceAddress(selectAddress);
  }, []);

  useEffect(() => {
    if (m3u8Anthology) {
      const hls = new Hls();
      hls.attachMedia((player.current as unknown as Player).video);
      hls.on(Hls.Events.MEDIA_ATTACHED, function () {
        hls.loadSource(currentSourceAddress || '');
      });

      const frag = document.createDocumentFragment();
      Quantity.itemElements =
        m3u8Anthology?.address.map((a) => {
          const el = document.createElement('div');
          el.textContent = a.current;
          el.classList.add('quantity_item');
          el.dataset.address = a.address;
          el.addEventListener('click', clickHandle as any);
          frag.appendChild(el);
          return el;
        }) || [];

      Quantity.popover?.panelEl.appendChild(frag);
      Quantity.el.style.display = 'block';
    }

    return () => {
      if (m3u8Anthology) {
        (Quantity.itemElements as HTMLDivElement[]).map((el) => el.removeEventListener('click', clickHandle as any));
        Quantity.popover.panelEl.innerHTML = '';
        Quantity.itemElements.length = 0;
        Quantity.popover.hide();
      }
    };
  }, [Quantity, clickHandle, currentSourceAddress, m3u8Anthology]);

  return (
    <div className="palyer-container-web">
      {m3u8Anthology ? (
        <div className="player-play-container">
          <div className="player-container">
            <div className="player-container" style={{ width: '100%', height: '100%' }}>
              <NPlayer
                ref={player}
                options={{
                  contextMenus: [Screenshot, 'loop', 'pip'],
                  controls: [
                    [
                      'play',
                      'volume',
                      'time',
                      'spacer',
                      Quantity,
                      'airplay',
                      'settings',
                      'web-fullscreen',
                      'fullscreen',
                    ],
                    ['progress'],
                  ],
                  volumeVertical: true,
                }}
              />
            </div>
            <div className="palyer-anthology"></div>
          </div>

          <div className="player-current-anthology">
            <div className="play-current-text">正片</div>
            <ul className="player-current-anthology-ul" onClick={clickHandle}>
              {m3u8Anthology?.address.map((add) => (
                <li
                  key={add.current}
                  data-address={add.address}
                  className={`player-anthology-item ${
                    currentSourceAddress === add.address ? 'player-anthology-item-active' : ''
                  }`}
                >
                  {add.current}
                </li>
              ))}
            </ul>
          </div>
        </div>
      ) : null}

      <div className="player-describe-container">
        <span className="img-container">
          <img src={pic} alt={name} className="img-pic" data-id={id} />
        </span>

        <span className="player-introduce-container">
          <span className="player-introduce">
            <span>影片名：</span>
            <span className="player-content-name" title={name || '无'} data-id={id}>
              {name || '无'}
            </span>
          </span>
          <span className="player-introduce">
            <span>
              演<span style={{ visibility: 'hidden' }}>员</span>员：
            </span>
            <span className="player-content player-content-actor" title={actor || '无'}>
              {actor || '无'}
            </span>
          </span>
          <span className="player-introduce">
            <span>
              简<span style={{ visibility: 'hidden' }}>介</span>介：
            </span>
            <span className="player-content" title={describe && describe !== 'undefined' ? describe : '无'}>
              {describe && describe !== 'undefined' ? describe : '无'}
            </span>
          </span>
        </span>
      </div>

      {anthology
        ?.filter((a) => !a.flag.includes('m3u8'))
        .map((s) => (
          <Card type="inner" title="其他播放源（跳转播放）" key={s.flag}>
            <ul className="player-current-anthology-ul">
              {s?.address.map((add) => (
                <li
                  key={add.current}
                  data-address={add.address}
                  className={`player-anthology-item ${
                    currentSourceAddress === add.address ? 'player-anthology-item-active' : ''
                  }`}
                >
                  <a href={add.address} target="_blank" rel="noreferrer">
                    {add.current}
                  </a>
                </li>
              ))}
            </ul>
          </Card>
        ))}
    </div>
  );
};

export const PlayerMobile: React.FC<VideosValueType> = () => {
  return <div></div>;
};
